/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {useContext, useState, useRef, useEffect} from 'react';
import {View, Text, ScrollView, TouchableOpacity, Dimensions, StyleSheet, Image} from 'react-native';
import type {ViewStyle} from 'react-native';
import {useBreakpointValue, useHeightBreakpointValue} from '@hadss/react_native_adaptive_layout';
import useDebounce from '../../hooks/useDebounce';
import Context from '../../Context';

const MODELIST = ['拍照', '录像'];
const DOT = require('../../../../../assets/pic/reddot.png')

/**
 * @description 滑动设置相机模式
 * @returns
 */
const ModeSetting = (props: {modeIndex: number; setModeIndex: Function}) => {
  const {isOpenVideo, setIsOpenVideo, isOpenPhoto, setIsOpenPhoto} = useContext(Context);
  const width = Dimensions.get('window').width;
  const ref = useRef<ScrollView>(null);
  const {setMode, isRecording} = useContext(Context);
  const [selectedIndex, setSelectedIndex] = useState(props.modeIndex);

  const isSmall = useHeightBreakpointValue<boolean>({
    base: false,
    sm: true,
    md: true,
    lg: false,
  });
  const currentBp = useBreakpointValue<string>({
    base: 'base',
    md: 'md',
    lg: 'lg',
  }) as string;

  /** 默认选中初始化，根据屏幕类型设置x | y */
  const handleSelected = useBreakpointValue<(index: number) => void>({
    base: index => ref?.current?.scrollTo?.({x: itemSize * index, animated: false}),
    md: index => ref?.current?.scrollTo?.({y: itemSize * index, animated: false}),
    lg: index => ref?.current?.scrollTo?.({y: 28 * index, animated: false}),
  });

  useEffect(() => {
    handleSelected?.(0);
  }, []);
  useEffect(() => {
    props.setModeIndex(selectedIndex);
  }, [selectedIndex]);

  const handleModeSetting = (index: number) => {
    setSelectedIndex(index);
    setIsOpenPhoto(index === 0);
    setIsOpenVideo(index === 1);
    setMode(index === 1 ? 'video' : 'photo');
  };
  const debouncedSetting = useDebounce(handleModeSetting, 30);

  const handleScroll = (e: any) => {
    const offsetX = e.nativeEvent.contentOffset.x;
    const index = Math.round(offsetX / itemSize);
    if (index >= 0 && index < MODELIST.length && index !== selectedIndex) {
      debouncedSetting(index);
    }
  };
  const handleScrollY = (e: any) => {
    const offsetY = e.nativeEvent.contentOffset.y;
    const index = Math.round(offsetY / itemSize);
    if (index >= 0 && index < MODELIST.length && index !== selectedIndex) {
      debouncedSetting(index);
    }
  };
  const handlePress = (index: number) => {
    if (index === selectedIndex) {
      return;
    }
    handleSelected?.(index);
  };

  /** horizontal模式下是item宽度 非horizontal模式下是item高度 需要把两边间距也算上 各取一半 */
  const itemSize = useBreakpointValue<number>({
    base: 56,
    md: 28,
    lg: 28,
  }) as number;

  const containerStyle = useBreakpointValue<ViewStyle>({
    base: isSmall
      ? {
          height: 32,
          marginBottom: 24,
          width: 144,
          marginLeft: (width - 144) / 2,
          opacity: isRecording ? 0 : 1,
        }
      : {
          height: 32,
          marginBottom: 24,
          marginTop: 32,
          opacity: isRecording ? 0 : 1,
        },
    md: {
      width: 90,
      height: 144,
      opacity: isRecording ? 0 : 1,
      position: 'absolute',
      zIndex: 5,
      bottom: 54,
      right: 0,
      alignItems: 'center',
    },
    lg: {
      width: 106,
      height: 144,
      opacity: isRecording ? 0 : 1,
      position: 'absolute',
      zIndex: 5,
      bottom: 42,
      right: 0,
      alignItems: 'center',
    },
  });

  const contentContainer = useBreakpointValue<ViewStyle>({
    base: isSmall
      ? {
          paddingHorizontal: (144 - itemSize) / 2,
        }
      : {
          // 这里设置是为了能够让第一个和最后一个能够滑动显示
          paddingHorizontal: (width - itemSize) / 2,
        },
    md: {paddingVertical: (144 - itemSize) / 2},
    lg: {paddingVertical: (144 - itemSize) / 2},
  });
  /** 不同屏幕类型注意适配 */
  const itemStyle = useBreakpointValue<ViewStyle>({
    base: {
      alignItems: 'center',
      justifyContent: 'center',
      width: itemSize,
      height: 20,
    },
    md: {
      alignItems: 'center',
      justifyContent: 'center',
      width: 50,
      height: 28,
    },
    lg: {
      alignItems: 'center',
      justifyContent: 'center',
      width: 50,
      height: 28,
    },
  });
  /** 是否水平根据端点值设置 */
  const horizontal = useBreakpointValue<boolean>({
    base: true,
    md: false,
    lg: false,
  });
  /** 指示器容器样式 */
  const indicator = useBreakpointValue<ViewStyle>({
    base: isSmall
      ? {
          height: 6,
          width: 6,
          position: 'absolute',
          bottom: 0,
          left: (144 - 6) / 2,
        }
      : {
          height: 6,
          width: 6,
          position: 'absolute',
          bottom: 0,
          left: (width - 6) / 2,
        },
    md: {
      height: 6,
      width: 6,
      position: 'absolute',
      right: 10,
      bottom: (144 - 6) / 2,
    },
    lg: {
      height: 6,
      width: 6,
      position: 'absolute',
      right: 10,
      bottom: (144 - 6) / 2,
    },
  });
  return (
    <View style={containerStyle}>
      <ScrollView
        ref={ref}
        horizontal={horizontal}
        showsHorizontalScrollIndicator={false}
        showsVerticalScrollIndicator={false}
        snapToInterval={itemSize}
        decelerationRate={'fast'}
        scrollEventThrottle={16}
        onScroll={currentBp === 'md' || currentBp === 'lg' ? handleScrollY : handleScroll}
        contentContainerStyle={contentContainer}
        disableIntervalMomentum>
        {MODELIST.map((item, index) => (
          <TouchableOpacity style={itemStyle} key={item} onPress={() => handlePress(index)}>
            <Text
              style={{
                ...styles.text,
                fontWeight: index === selectedIndex ? '600' : '400',
                color: index === selectedIndex ? 'rgba(255, 255, 255, 1)' : 'rgba(255, 255, 255, 0.9)',
              }}>
              {item}
            </Text>
          </TouchableOpacity>
        ))}
      </ScrollView>
      <View style={indicator}>
        <Image source={DOT} style={{width: 6, height: 6}} />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  text: {
    color: 'rgba(255, 255, 255, 1)',
    fontSize: 14,
    lineHeight: 20,
  },
});

export default ModeSetting;
